import {
  SET_MOVE_DIRECTLY_OPS_FORM,
  SET_MOVE_DIRECTLY_DATA_LIST,
  SET_MOVE_DIRECTLY_DATA_ID,
  CLEAR_MOVE_DIRECTLY_DATA_ID,
  CLEAR_MOVE_DIRECTLY_OPS_FORM,
  SET_MOVE_DIRECTLY_DETAILS,
  DEL_MOVE_DIRECTLY_DETAILS
} from "./action-types";

const initialState = {
  dataList: [],
  dataListOffset: 0,

  opsFormData: null,

  dataId: null,
  details: []
};

const handleDataList = (state, payload) => {
  let { items, offset } = payload;
  if (items.length === 0 && offset === 0) {
    return { ...state, dataList: [], dataListOffset: 0 };
  } else {
    return {
      ...state,
      dataList: state.dataList.concat(items),
      dataListOffset: offset
    };
  }
};

const handleDelDetails = (state, payload) => {
  return {
    ...state,
    details: state.details.filter((i) => i.id !== payload.id),
  };
};

const data = (state = initialState, action) => {
  switch (action.type) {
    case SET_MOVE_DIRECTLY_DATA_LIST:
      return handleDataList(state, action.payload);
    case SET_MOVE_DIRECTLY_OPS_FORM:
      return { ...state, opsFormData: action.payload };
    case SET_MOVE_DIRECTLY_DATA_ID:
      return {
        ...state,
        dataId: action.payload.id,
        opsFormData: {
          ...state.opsFormData,
          recordNum: action.payload.recordNum,
        },
      };
    case CLEAR_MOVE_DIRECTLY_DATA_ID:
      return { ...state, dataId: null, opsFormData: null };
    case CLEAR_MOVE_DIRECTLY_OPS_FORM:
      return { ...state, opsFormData: null };
    case SET_MOVE_DIRECTLY_DETAILS:
      return { ...state, details: action.payload.items };
    case DEL_MOVE_DIRECTLY_DETAILS:
      return handleDelDetails(state, action.payload);
    default:
      return state;
  }
};

export default data;
